<template>
  <div id="lineChart" style="height:400px"></div>
</template>

<script>
  import mdata from '../../static/tmpData'
  import eventBus from '../utils/eventBus'
	import * as echarts from 'echarts'
  import { categories, indexOfRow } from '../utils/categories'
  
	const shareColor = function (info) {
	  const num = typeof info === 'object' ? (info.currentPrice * 1 - info.lastPrice * 1) : (info * 1)
		if (isNaN(num))return ''
		if (num < 0) {
			return 'green'
		}
		if (num > 0) {
			return 'red'
		}
		return ''
	}
	const toDecimal2 = function (x, size){
		if (x === '0E-8') return "0.00"
		if (x === '--') return x
		size = !size && size !== 0 ? 2 : size
		var f = parseFloat(x)
		if (isNaN(f)) {
			return '0.00'
		}
		var f = f.toFixed(size)
		var s = f.toString()
		var rs = s.indexOf('.')
		if (rs < 0 && size !== 0) {
			rs = s.length
			s += '.'
		}
		while (s.length <= rs + size) {
			s += '0'
		}
		return s
	}
  const sleep = (time) => {
    return new Promise(resolve => setTimeout(resolve, time))
  }

  export default {
		name: "time-share",
		data: function () {
			return {
        echarts: null,
        timer: null,
				option: {}
			}
		},
    props: {
      data: {
        type: Object,
        default: null
      },
      speed: {
        type: Number,
        default: 1000
      },
      pulse: {
        type: Boolean,
        default: false
      },
      startPlayTime: {
        type: String,
        default: '21:00'
      }
    },
    mounted(){
      this.initChart()
      eventBus.$on('pulseOn', event => {
        if (event) {
          this.playTimeSharing()
        } else {
          clearInterval(this.timer)
        }
      }),
      this.$on('currentTime', data => {
        let newData = this.formatData(data)
        this.setOption(newData)
      }),
      this.$on('level5Steep', (currentTime, steep) => {
        let data = mdata(currentTime.replace(':', ''))
        let newData = this.formatData(data)
        this.level5PriceSteep(newData, steep)
      })
    },
    watch: {
      
    },
    methods: {
      formatData(data) {
        let price = data.minLine
        let volumn = data.volumns
        let lastPrice = data.lastPrice * 1
        let avgPrice = data.avgLine
        let currentTime = categories[price.length - 1]
        let currentPrice = price[price.length - 1] * 1 == 0 ? lastPrice : price[price.length - 1]
        let highPrice = data.highPrice
        let lowPrice = data.lowPrice
        let chajia = Math.abs(highPrice - lastPrice) >= Math.abs(lowPrice - lastPrice) ? Math.abs(highPrice - lastPrice) : Math.abs(lowPrice - lastPrice)
        let high = (lastPrice + chajia).toFixed(2)
        let low = (lastPrice - chajia).toFixed(2)
        if (!!data.time && data.time[data.time.length - 1] === "15:00") {
          currentPrice = null
          currentTime = null
        }

        let maxVolum = 0
        let highPoint = []
        let openLine = []
        let volumns = []
        for (let i = 0, length = categories.length; i < length; i++) {
          let lp = 0
          if (i == 0) {
            lp = lastPrice
          } else {
            lp = price[i] ? price[i - 1] : 0
          }
          let v = volumn[i] ? volumn[i] : 0
          maxVolum = v >= maxVolum ? v : maxVolum

          let np = price[i] ? price[i] == 0 ? lastPrice : price[i] : 0

          highPoint = [price.length - 1, price[length - 1]]
          openLine[i] = {
            name: categories[i],
            value: lastPrice + ""
          }
          volumns[i] = {
            name: categories[i],
            value: volumn[i] ? volumn[i] : 0,
            itemStyle: {
              normal: {
                color: np - lp > 0 ? "#FF0D00" : '#43a950'
              }
            }
          }
        }

        return {
          price: price,
          lastPrice: lastPrice,
          currentPrice: currentPrice,
          currentTime: currentTime,
          high: high,
          low: low,
          maxVolum: maxVolum,
          chajia:chajia,
          avgPrice: avgPrice,
          volumns: volumns,
          openLine: openLine,
          level5: data.level5,
          time: data.time,
          totalVolume: data.totalVolume
        }
      },
      initChart() {
        this.echarts = echarts.init(document.getElementById('lineChart'))
      },
      playTimeSharing() {
        var c = indexOfRow(this.startPlayTime)
        // console.log(c+ '%%' +this.startPlayTime)
        this.timer = setInterval(() => {
          let data = mdata(categories[c].replace(':', ''))
          let newData = this.formatData(data)
          this.setOption(newData)
          this.level5Price(newData)
          c += 1
          if (c >= categories.length) {
            clearInterval(this.timer)
          }
         }, this.speed);
      },
      async setOption(formatedData){
        let $this = this
        //console.log(formatedData)
        let price = formatedData.price
        let lastPrice = formatedData.lastPrice * 1
        let low = 31 //formatedData.low
        let high = 36 //formatedData.high
        let maxVolum = formatedData.maxVolum
        let chajia = 4 //formatedData.chajia
        let avgPrice = formatedData.avgPrice
        let volumns = formatedData.volumns
        let currentPrice = formatedData.currentPrice
        let currentTime = formatedData.currentTime
        let openLine = formatedData.openLine
        let markPoint = [[currentTime, currentPrice]]
        let showMiddleValue = 0.00
        let lable = []
        let totalTraded = formatedData.totalVolume

        let option = {
          //animationDurationUpdate: 300,
          //animationDuration: 10000,
          tooltip: {
            trigger: 'axis',
            // transitionDuration: 0,
            axisPointer: {
              type: 'cross',
              animation: false,
              label: {
                backgroundColor: '#ccc',
                borderColor: '#aaa',
                borderWidth: 2,
                shadowBlur: 0,
                shadowOffsetX: 0,
                shadowOffsetY: 0,
                color: '#222'
              }
            },
            textStyle: {
              color: "#3d3d3d"
            },
            position: function (pt, arr, dom) {
              return [0, 0]
            },
            extraCssText: "width:100%height:0pxmargin-left:0%padding:0px",
            formatter: function (param) {
              let chart = $this.echarts
              let top1 = chart.convertToPixel({yAxisIndex: 0}, high)
              let height = chart.convertToPixel({yAxisIndex: 1}, 0) - top1
              let left1 = chart.convertToPixel({xAxisIndex: 1}, 0)
              let width = chart.convertToPixel({xAxisIndex: 1}, openLine.length - 1) - left1
              let type = param[0].componentSubType
              let index = 0
              let time = ""

              if (type === "bar") {
                index = param[0].dataIndex
                time = param[0].name
              } else if(param[2]) {
                index = param[2].dataIndex
                time = param[2].name
              }
              if (index >= formatedData.time.length - 1) {
                index = formatedData.time.length - 1
              }
              let color = shareColor({
                currentPrice: price[index] == 0 ? lastPrice : price[index],
                lastPrice: lastPrice
              })

              let nowTime = formatedData.time[index]
              let avg = avgPrice[index]
              let vol = volumns[index].value
              let p = toDecimal2(price[index] == 0 ? lastPrice : price[index])
              let top = chart.convertToPixel({yAxisIndex: 0}, p * 1)
              let left = chart.convertToPixel({xAxisIndex: 1}, index)
              let zd = (p * 1 - lastPrice * 1).toFixed(2)
              let zf = (zd * 100 / lastPrice).toFixed(2)
              let totalTra = totalTraded >= 10000 ? (totalTraded / 10000).toFixed(2) + "万" : totalTraded
              let dataText = "<p>时间:<span style='float:right'>" + nowTime + "</span></p>" +
                "<p>价位:<span style='float:right' class='" + color + "'>" + p + "</span></p>" +
                "<p>均价:<span style='float:right' class='" + color + "'>" + avg + "</span></p>" +
                "<p>涨跌:<span style='float:right' class='" + color + "'>" + zd + "</span></p>" +
                "<p>涨幅:<span style='float:right' class='" + color + "'>" + zf + "%</span></p>" +
                "<p>现量:<span style='float:right'>" + vol + "</span></p>" +
                "<p>总量:<span style='float:right'>" + totalTra + "</span></p>"

              let leftText = "<div style='position:absoluteborder:1px #B4CCFC solidz-index:33width:90pxheight:150pxtop:" + top1 + "pxleft:" + left1 + "pxbackground-color:rgba(255,255,255,0.7)'>"
              let rightText = "<div style='position:absoluteborder:1px #B4CCFC solidz-index:33width:90pxheight:150pxtop:" + top1 + "pxright:" + left1 + "pxbackground-color:rgba(255,255,255,0.7)'>"
              let text = ""
              let crossText = "<div style='position:absolutewidth:1pxheight:" + height + "pxbackground-color:#00A0E8top:" + top1 + "pxleft:" + left + "px'></div>" +
                "<div style='position:absoluteheight:1pxwidth:" + width + "pxbackground-color:#00A0E8top:" + top + "pxleft:" + left1 + "px'></div>"
              if (index >= categories.length / 2) {
                text = leftText + dataText + "</div>" + crossText
              } else {
                text = rightText + dataText + "</div>" + crossText
              }

              return text
            }
          },
          grid: [
            {
              left: 60,
              right: 60,
              top: "5%",
              height: '63.19%',
              containLabel:false,
              show: true,
              borderWidth: 0,
              boderColor: "#d0d0d0",
              shadowBlur: 0
            },
            {
              left: 60,
              right: 60,
              height: '26.82%',
              top: '68.19%',
              containLabel:false,
              show: false,
              borderWidth: 0,
              boderColor: "#d0d0d0",
              shadowBlur: 0,
          }],
          parallel: {height: 300,width:350},
          xAxis: [
            {
              type: 'category',
              gridIndex: 0,
              data: categories,
              min: 'dataMin',
              max: 'dataMax',
              axisLine: {
                show: false
              },
              axisLabel: {
                fontWeight: "bold",
                interval: 29,
                show: false,
                textStyle: {
                  color: '#3d3d3d',
                  shadowColor: "rgba(0,0,0,0)",
                  fontWeight: "bold",
                }
              },
              axisTick: {
                show: false
              },
              splitLine: {
                show: true,
                lineStyle: {
                  width: 0.3,
                  color: '#DDDDDD',
                  shadowColor: "rgba(0,0,0,0)"
                },
              },
              boundaryGap: false
            },
            {
              type: 'category',
              gridIndex: 1,
              data: categories,
              axisLine: {
                lineStyle: {
                  width: 0.3,
                  color: '#d0d0d0',
                  shadowColor: "rgba(0,0,0,0)"
                },
                show: true
              },
              axisLabel: {
                interval: 29,
                show: true,
                textStyle: {
                  fontSize: 12,
                  color: "#3d3d3d",
                  fontWeight: "bold",
                }
              },
              splitLine: {
                show: true,
                lineStyle: {
                  width: 0.3,
                  color: '#DDDDDD'
                },
              },
            }
          ],
          yAxis: [
            {
              type: 'value',
              position: "left",
              offset:0,
              gridIndex: 0,
              interval: chajia / 4,
              min: low,
              max: high,
              axisLine: {
                show: false
              },
              axisTick: {show: false},
              axisLabel: {
                show: true,
                formatter: function (value, index) {
                  value = value * 1
                  if (index == 4) {
                    showMiddleValue = value.toFixed(2) * 1
                    value = lastPrice
                  }
                  return value.toFixed(2)
                },
                margin: 1,
                textStyle: {
                  fontSize: 12,
                  fontWeight: "bold",
                  color: function (val) {
                    val = val.replace(",", "") * 1
                    val = val.toFixed(2) * 1
                    if (val > showMiddleValue) {
                      return "#ff0d00"
                    }
                    else if (val < showMiddleValue) {
                      return '#43a950'
                    } else {
                      return "#3d3d3d"
                    }
                  }
                }
              },
              splitLine: {
                show: true,
                lineStyle: {
                  width: 0.3,
                  color: '#dddddd',
                }
              },
            },
            {
              type: 'value',
              position: "left",
              offset:0,
              gridIndex: 1,
              max: maxVolum,
              min: 0,
              interval: ((maxVolum / 3).toFixed(2)) * 1,
              axisTick: {show: false},
              axisLabel: {
                show: true,
                margin: 1,
                formatter: function (value, index) {
                  if (index != 3) {
                    lable[index] = value
                    return value
                  }
                },
                textStyle: {
                  fontWeight: "bold",
                  color: "#3d3d3d",
                  fontSize: 12
                }
              },
              splitLine: {
                show: true,
                lineStyle: {
                  width: 0.3,
                  color: '#d0d0d0'
                }
              }
            },
            {
              type: 'value',
              position: "right",
              min: low,
              max: high,
              gridIndex: 0,
              interval: (chajia / 4),
              axisTick: {show: false},
              axisLabel: {
                show: true,
                margin: 1,
                fontWeight: "bold",
                formatter: function (value, index) {
                  if (index == 4) {
                    showMiddleValue = value
                    value = "0.00%"
                  } else {
                    value = ((Math.abs(value - lastPrice) / lastPrice) * 100).toFixed(2)
                    value = value + "%"
                  }
                  return value
                },
                textStyle: {
                  fontSize: 12,
                  color: function (val) {
                    val = val.replace(",", "") * 1
                    val = val.toFixed(2) * 1
                    if (val > showMiddleValue) {
                      return "#ff0d00"
                    }
                    else if (val < showMiddleValue) {
                      return '#43a950'
                    } else {
                      return "#3d3d3d"
                    }
                  },
                  fontWeight: "bold",
                }
              },
              splitLine: {
                show: false
              }
            },
            {
              type: 'value',
              position: "right",
              min: 0,
              max: maxVolum,
              gridIndex: 1,
              interval: ((maxVolum / 3).toFixed(2)) * 1,
              axisTick: {show: false},
              axisLabel: {
                show: true,
                margin: 1,
                formatter: function (value, index) {
                  if (index != 3) {
                    return lable[index]
                  }
                },
                textStyle: {
                  fontWeight: "bold",
                  color: '#3d3d3d',
                  fontSize: 12,
                }

              },
              splitLine: {
                show: false
              },
              axisLine: {
                show: false
              },
            }
          ],
          series: [
            {
              name: '分时',
              type: 'line',
              smooth: false,
              showSymbol: false,
              symbol: 'circle',
              symbolSize: 0,
              data: price,
              xAxisIndex: 0,
              yAxisIndex: 0,
              sampling: 'average',
              lineStyle: {
                normal: {
                  color: "#66b6ff",
                  width: 1
                }
              },
              itemStyle: {
                normal: {
                  areaStyle: {
                    type: 'default', color: new echarts.graphic.LinearGradient(0, 0, 0, 1, [{
                      offset: 0,
                      color: 'rgb(238, 250, 255)'
                    }, {
                      offset: 1,
                      color: 'rgb(250, 254, 255)'
                    }])
                  }
                }
              },
            },
            {
              name: '均线',
              type: 'line',
              smooth: false,
              showSymbol: false,
              symbol: 'circle',
              symbolSize: 0,
              xAxisIndex: 0,
              yAxisIndex: 0,
              data: avgPrice,
              lineStyle: {
                normal: {
                  color: "#ffC500",
                  width: 1,
                  type: "solid"
                }
              },
            },
            {
              name: '昨收',
              type: 'line',
              smooth: true,
              symbol: 'none',
              sampling: 'average',
              xAxisIndex: 0,
              yAxisIndex: 0,
              lineStyle: {
                normal: {
                  color: "#ccc",
                  type: 'dashed',
                  width: 1
                }
              },
              data: openLine,
            },
            {
              name: 'Volumn',
              type: 'bar',
              boundaryGap: true,
              legendHoverLink: false,
              xAxisIndex: 1,
              yAxisIndex: 1,
              itemStyle: {
                normal: {
                  color: '#7fbe9e'
                }
              },
              data: volumns
            },
            {
              name: '最新',
              type: 'effectScatter',
              boundaryGap: true,
              rippleEffect: {
                period: 4,
                scale: 3,
                brushType: 'stroke',
              },
              symbolSize: 4,
              xAxisIndex: 0,
              yAxisIndex: 0,
              itemStyle: {
                normal: {
                  color: '#66b6ff'
                }
              },
              coordinateSystem: "cartesian2d",
              data: markPoint
            }
          ]
        }
        this.option = option
        this.echarts.setOption(option)
        //var i = 0
        // let timer = setInterval(() => {
        //   this.echarts.appendData({
        //     seriesIndex: 0,
        //     data: price.slice(i * 10 , (i + 1) * 10),
        //   });
        //   this.echarts.resize();
        //   i += 1
        //   if (i >= price.length / 10) {
        //     clearInterval(timer)
        //   }
         
        //  }, 1000);

        //
      },
      async level5Price(formatedData) {
        let level5 = formatedData.level5.pop()
        let price = formatedData.price
        let avgPrice = formatedData.avgPrice
        let volumns = formatedData.volumns
        let markPoint = formatedData.markPoint
        let openLine = formatedData.openLine
        for (var i = 0; i < level5.length ; i ++) {
          await sleep(this.speed/4);
          price.pop()
          price.push(level5[i])
          //console.log(formatedData.currentTime + ':' + level5[i])
          this.echarts.setOption({
            xAxis: [
                {
                  data: categories
                },
                {
                  data: categories
                }
            ],
            series: [
              {
                data: price
              },
              {
                data: avgPrice
              },
              {
                data: openLine
              },
              {
                data: volumns
              },
              {
                data: markPoint
              }
            ]})
        } 
      },
      async level5PriceSteep(formatedData, steep) {
        let level5 = formatedData.level5.pop()
        let price = formatedData.price
        let avgPrice = formatedData.avgPrice
        let volumns = formatedData.volumns
        let markPoint = formatedData.markPoint
        let openLine = formatedData.openLine
        price.pop()
        price.push(level5[steep])
        this.echarts.setOption({
          xAxis: [
            {
              data: categories
            },
            {
              data: categories
            }
          ],
          series: [
            {
              data: price
            },
            {
              data: avgPrice
            },
            {
              data: openLine
            },
            {
              data: volumns
            },
            {
              data: markPoint
            }
          ]})
      }
    }
	}
</script>

<style type="text/css">

</style>
